import time
import logging
import re
import os
import config
from airtest.core.android import Android
from utils import retry

logger = logging.getLogger(__name__)


class PerformanceMonitor:
    def __init__(self, dev: Android, package_name):
        self.dev = dev
        self.package_name = package_name
        self.pid = None
        self._monitoring = False
        self.performance_data = []
        self._is_app_running = True

        # CPU计算相关属性
        self._last_proc_time = None
        self._last_sys_time = None
        self._last_sample_time = time.time()
        self.cpu_cores = self.get_cpu_cores()

        # FPS平滑处理相关属性
        self._fps_history = []

        self.thresholds = config.PERFORMANCE_THRESHOLDS
        self.exceeded_thresholds = []

    def get_cpu_cores(self):
        """获取CPU核心数"""
        try:
            output = self.dev.shell("cat /proc/cpuinfo | grep processor | wc -l")
            return int(output.strip()) or 1
        except:
            return 1

    def check_thresholds(self, data):
        """检查实时数据是否超过阈值并标记"""
        exceeded = {}

        # 物理内存检查
        if 'memory' in data and 'rss' in data['memory']:
            rss = data['memory']['rss']
            if rss > self.thresholds['rss_memory']['peak']:
                exceeded['rss_peak'] = rss

        # 虚拟内存检查
        if 'memory' in data and 'virt' in data['memory']:
            virt = data['memory']['virt']
            if virt > self.thresholds['virt_memory']['peak']:
                exceeded['virt_peak'] = virt

        # CPU检查
        if 'cpu' in data and data['cpu'] is not None:
            cpu = data['cpu']
            if cpu > self.thresholds['cpu']['peak']:
                exceeded['cpu_peak'] = cpu

        # FPS检查
        if 'fps' in data and data['fps'] is not None:
            fps = data['fps']
            if fps < self.thresholds['fps']['min']:
                exceeded['fps_min'] = fps

        # 温度检查
        if 'temperature' in data and data['temperature'] is not None:
            temp = data['temperature']
            if temp > self.thresholds['temperature']['peak']:
                exceeded['temp_peak'] = temp

        # 如果有超阈值项，记录到数据中
        if exceeded:
            data['exceeded_thresholds'] = exceeded
            self.exceeded_thresholds.append({
                "timestamp": data["timestamp"],
                "exceeded": exceeded
            })

    def get_cpu_cores(self):
        """获取CPU核心数"""
        try:
            output = self.dev.shell("cat /proc/cpuinfo | grep processor | wc -l")
            return int(output.strip()) or 1
        except:
            return 1

    @retry(times=2, delay=1)
    def get_pid(self, force_refresh=False):
        """获取应用进程PID，可选择强制刷新"""
        if force_refresh:
            new_pid = self._get_pid()
            if new_pid and new_pid != self.pid:
                self.pid = new_pid
            return self.pid

        if self.pid:
            return self.pid

        self.pid = self._get_pid()
        return self.pid

    def _get_pid(self):
        """获取应用进程PID - 增强版本"""
        try:
            # 方法1: 使用pidof命令
            logger.debug(f"尝试通过pidof命令获取{self.package_name}的PID")
            output = self.dev.shell(f"pidof {self.package_name}")
            if output.strip().isdigit():
                logger.debug(f"成功从pidof命令获取PID: {output.strip()}")
                return output.strip()

            # 方法2: 使用ps命令
            logger.debug(f"尝试通过ps命令获取{self.package_name}的PID")
            output = self.dev.shell(f"ps -A | grep {self.package_name}")
            if output:
                lines = output.strip().split('\n')
                for line in reversed(lines):
                    parts = line.strip().split()
                    if len(parts) >= 2 and self.package_name in parts[-1]:
                        logger.debug(f"成功从ps命令获取PID: {parts[1]}")
                        return parts[1]

            # 方法3: 使用dumpsys activity
            logger.debug(f"尝试通过dumpsys activity获取{self.package_name}的PID")
            output = self.dev.shell("dumpsys activity activities")
            if output:
                lines = output.strip().split('\n')
                for line in lines:
                    if self.package_name in line and "pid=" in line:
                        match = re.search(r'pid=(\d+)', line)
                        if match:
                            pid = match.group(1)
                            logger.debug(f"成功从dumpsys activity获取PID: {pid}")
                            return pid

            logger.debug(f"无法获取{self.package_name}的PID")
            return None
        except Exception as e:
            logger.debug(f"获取PID时发生错误: {str(e)}")
            return None

    @retry(times=2, delay=1)
    def is_app_running(self):
        """检查应用是否仍在运行"""
        if not self.pid:
            # 尝试刷新PID
            self.pid = self.get_pid(force_refresh=True)
            if not self.pid:
                return False

        try:
            # 检查PID是否仍在运行
            output = self.dev.shell(f"ps -p {self.pid}")
            self._is_app_running = str(self.pid) in output
            return self._is_app_running
        except:
            # 发生异常时尝试刷新PID
            self.pid = self.get_pid(force_refresh=True)
            return False

    @retry(times=2, delay=1)
    def get_memory_usage(self, include_virtual=False):
        """获取内存使用情况，包含虚拟内存选项"""
        if not self.is_app_running():
            logger.debug(f"应用 {self.package_name} 已退出，无法获取内存使用信息")
            return None

        try:
            # 获取物理内存（RSS）
            rss = self._get_rss_memory()

            # 获取虚拟内存（VIRT）
            virt = None
            if include_virtual:
                virt = self._get_virtual_memory()

            # 返回组合结果
            if include_virtual:
                return {"rss": rss, "virt": virt}
            return rss

        except Exception as e:
            logger.error(f"获取内存使用情况失败: {str(e)}")
            return None

    @retry(times=3, delay=1)
    def _get_rss_memory(self):
        """获取物理内存使用情况（RSS） - 优化解析逻辑"""
        try:
            # 方法1：优先使用/proc/<pid>/status（最可靠）
            pid = self.get_pid()
            if pid:
                status_output = self.dev.shell(f"cat /proc/{pid}/status")
                for line in status_output.splitlines():
                    if line.startswith("VmRSS:"):
                        parts = line.split()
                        if len(parts) >= 2:
                            try:
                                rss_kb = int(parts[1])
                                if 1000 < rss_kb < 500000:  # 合理范围检查
                                    logger.debug(f"通过/proc/status获取RSS: {rss_kb} KB")
                                    return rss_kb
                            except (ValueError, IndexError):
                                pass

            # 方法2：使用dumpsys meminfo（增强解析）
            if self.pid:
                output = self.dev.shell(f"dumpsys meminfo {self.pid}")
            else:
                output = self.dev.shell(f"dumpsys meminfo '{self.package_name}'")

            # 优化解析逻辑 - 兼容多种ROM格式
            for line in output.splitlines():
                # 匹配TOTAL行（兼容不同大小写和符号）
                if re.search(r'(TOTAL|Total RAM|Total PSS|Total)', line, re.IGNORECASE):
                    # 提取所有数字（兼容逗号分隔和单位）
                    numbers = re.findall(r'(\d{1,3}(?:,\d{3})*)\s*(?:kB|KB)?\b', line)
                    if numbers:
                        try:
                            # 通常最后一个数字是总值
                            total_kb = int(numbers[-1].replace(',', ''))
                            if 1000 < total_kb < 500000:  # 有效范围检查
                                logger.debug(f"通过dumpsys TOTAL行获取: {total_kb} KB")
                                return total_kb
                        except ValueError:
                            continue

                # 匹配Native/RSS行（某些ROM单独列出）
                if "Native Heap" in line and "RSS:" in line:
                    parts = line.split()
                    try:
                        rss_index = parts.index("RSS:") + 1
                        rss_kb = int(parts[rss_index].replace(',', ''))
                        logger.debug(f"通过Native Heap RSS获取: {rss_kb} KB")
                        return rss_kb
                    except (ValueError, IndexError):
                        continue

            # 方法3：使用top命令（直接获取实时内存）
            try:
                top_output = self.dev.shell(f"top -n 1 -p {pid}")
                for line in top_output.splitlines():
                    if str(pid) in line:
                        parts = line.split()
                        # 通常RSS在第6列（VSS RSS PCY ...）
                        if len(parts) > 6:
                            rss_str = parts[5].strip('K')  # 移除可能的K后缀
                            rss_kb = int(rss_str)
                            if 1000 < rss_kb < 500000:
                                logger.debug(f"通过top命令获取RSS: {rss_kb} KB")
                                return rss_kb
            except Exception:
                pass

            # 方法4：使用procrank作为最后手段
            try:
                procrank_output = self.dev.shell("procrank | grep {}".format(pid))
                if not procrank_output:
                    return None

                for line in procrank_output.splitlines():
                    parts = line.split()
                    if len(parts) >= 5:
                        # RSS通常在第5列（PID Vss Rss Pss Uss）
                        rss_kb = int(parts[4].replace(',', ''))
                        logger.debug(f"通过procrank获取RSS: {rss_kb} KB")
                        return rss_kb
            except Exception:
                pass

            logger.warning("所有内存获取方法均失败")
            return None

        except Exception as e:
            logger.error(f"获取物理内存失败: {str(e)}")
            return None

    def _fallback_memory_methods(self):
        """备用内存获取方法"""
        try:
            output = self.dev.shell("procrank")
            for line in output.splitlines():
                if self.package_name in line:
                    parts = line.split()
                    if len(parts) > 5:
                        try:
                            memory = int(parts[4])  # RSS在第五列
                            logger.debug(f"内存使用: {memory} KB (procrank)")
                            return memory
                        except (IndexError, ValueError):
                            pass
        except Exception as e:
            logger.debug(f"procrank失败: {str(e)}")

        # 方法3: /proc/<pid>/status
        try:
            pid = self.get_pid()
            if pid:
                output = self.dev.shell(f"cat /proc/{pid}/status")
                for line in output.splitlines():
                    if "VmRSS:" in line:
                        parts = line.split()
                        if len(parts) >= 2:
                            return int(parts[1])  # 单位KB
        except Exception as e:
            logger.debug(f"/proc status失败: {str(e)}")

        logger.warning("所有内存获取方法均失败")
        return None

    @retry(times=2, delay=1)
    def _get_virtual_memory(self):
        """获取虚拟内存使用情况（VIRT） - 增强错误处理"""
        try:
            pid = self.get_pid(force_refresh=True)
            if not pid:
                return None

            # 首先检查进程是否存在
            try:
                # 使用 ps 命令检查进程是否存在
                output = self.dev.shell(f"ps -p {pid}")
                if not output or str(pid) not in output:
                    logger.debug(f"进程 {pid} 不存在，无法获取虚拟内存")
                    return None
            except Exception as e:
                logger.debug(f"检查进程存在性失败: {str(e)}")
                # 继续尝试获取虚拟内存

            # 优先使用procrank命令（如果可用）
            try:
                # 尝试直接调用procrank
                output = self.dev.shell(f"procrank -p {pid}")
                if output:
                    for line in output.split('\n'):
                        if str(pid) in line:
                            parts = line.split()
                            if len(parts) >= 6:
                                # VIRT 通常在第5列（VSS）
                                try:
                                    virt = int(parts[4])
                                    logger.debug(f"虚拟内存: {virt} KB (procrank)")
                                    return virt
                                except:
                                    pass
            except:
                # 如果procrank不可用，尝试其他方法
                pass

            # 备选方法：从/proc/<pid>/status获取
            try:
                output = self.dev.shell(f"cat /proc/{pid}/status")
                if output:
                    for line in output.split('\n'):
                        if "VmSize:" in line:
                            parts = line.split()
                            if len(parts) >= 2:
                                try:
                                    virt = int(parts[1])  # 单位是KB
                                    logger.debug(f"虚拟内存: {virt} KB (VmSize)")
                                    return virt
                                except:
                                    pass
            except:
                pass

            # 最后尝试：从/proc/<pid>/stat获取
            try:
                output = self.dev.shell(f"cat /proc/{pid}/stat")
                if output:
                    parts = output.split()
                    if len(parts) > 22:
                        try:
                            # 第22列是虚拟内存大小（页面数）
                            virt_pages = int(parts[22])
                            # 转换为KB（通常页面大小为4KB）
                            virt = virt_pages * 4
                            logger.debug(f"虚拟内存: {virt} KB (stat)")
                            return virt
                        except:
                            pass
            except:
                pass

            logger.debug("无法获取虚拟内存信息")
            return None
        except Exception as e:
            logger.debug(f"获取虚拟内存失败: {str(e)}")
            return None

    @retry(times=3, delay=1)
    def get_cpu_usage(self):
        """使用top命令获取更准确的CPU使用率 - 增强错误处理"""
        try:
            # 获取PID
            pid = self.get_pid(force_refresh=True)
            if not pid:
                return None

            # 使用top命令获取CPU使用率
            output = self.dev.shell(f"top -n 1 -d 0.5 -b -p {pid}")
            if not output:
                return self._get_cpu_usage_fallback()

            # 解析top输出
            lines = output.split('\n')
            for i, line in enumerate(lines):
                if str(pid) in line:
                    # 提取包含CPU使用率的行
                    parts = line.split()

                    # 不同Android版本top输出格式不同
                    if len(parts) >= 9:
                        # 尝试第9列（通常是CPU%）
                        cpu_str = parts[8].replace('%', '').replace('R', '').replace('S', '')
                        try:
                            cpu_usage = float(cpu_str)
                            logger.debug(f"CPU使用率: {cpu_usage}% (top命令)")
                            return cpu_usage
                        except ValueError:
                            # 尝试第10列
                            if len(parts) >= 10:
                                cpu_str = parts[9].replace('%', '')
                                try:
                                    cpu_usage = float(cpu_str)
                                    logger.debug(f"CPU使用率: {cpu_usage}% (top命令-备选列)")
                                    return cpu_usage
                                except ValueError:
                                    pass

                    # 有些设备格式不同，尝试从下一行获取
                    if i + 1 < len(lines):
                        next_line = lines[i + 1]
                        if "CPU:" in next_line:
                            match = re.search(r'CPU:\s*(\d+\.?\d*)%', next_line)
                            if match:
                                try:
                                    cpu_usage = float(match.group(1))
                                    logger.debug(f"CPU使用率: {cpu_usage}% (top命令-特殊格式)")
                                    return cpu_usage
                                except:
                                    pass

            # 如果无法解析，回退到原有方法
            logger.debug("无法解析top输出，使用备选CPU计算方法")
            return self._get_cpu_usage_fallback()

        except Exception as e:
            logger.error(f"获取CPU使用率失败: {str(e)}")
            return self._get_cpu_usage_fallback()

    def _get_cpu_usage_fallback(self):
        """备选CPU获取方法 - 使用/proc/stat"""
        if not self.is_app_running():
            return None

        try:
            # 方法1: 使用/proc/stat计算
            if self.pid:
                try:
                    # 获取进程CPU时间
                    proc_stat = self.dev.shell(f"cat /proc/{self.pid}/stat")
                    if proc_stat:
                        proc_parts = proc_stat.split()
                        if len(proc_parts) >= 17:
                            utime = int(proc_parts[13])
                            stime = int(proc_parts[14])
                            cutime = int(proc_parts[15])
                            cstime = int(proc_parts[16])
                            proc_time = utime + stime + cutime + cstime

                        # 获取系统总CPU时间
                        sys_stat = self.dev.shell("cat /proc/stat | grep '^cpu '")
                        if sys_stat:
                            sys_parts = sys_stat.split()
                            sys_time = sum(int(sys_parts[i]) for i in range(1, 8))

                            # 计算CPU使用率
                            if hasattr(self, '_last_proc_time') and hasattr(self, '_last_sys_time'):
                                proc_diff = proc_time - self._last_proc_time
                                sys_diff = sys_time - self._last_sys_time

                                # 计算时间间隔（秒）
                                current_time = time.time()
                                time_interval = current_time - self._last_sample_time
                                self._last_sample_time = current_time

                                if sys_diff > 0 and time_interval > 0:
                                    cpu_usage = 100 * (proc_diff / sys_diff) * self.cpu_cores / time_interval
                                    # 过滤异常值
                                    if 0 <= cpu_usage <= 1000:
                                        logger.debug(f"CPU使用率: {cpu_usage}% (/proc/stat)")
                                        return cpu_usage

                            # 保存当前值供下次计算
                            self._last_proc_time = proc_time
                            self._last_sys_time = sys_time
                except Exception as e:
                    logger.debug(f"使用/proc/stat计算CPU失败: {str(e)}")

            # 方法2: 使用dumpsys cpuinfo
            try:
                output = self.dev.shell("dumpsys cpuinfo")
                if output:
                    for line in output.splitlines():
                        if self.package_name in line:
                            match = re.search(r'(\d+\.\d+)%', line)
                            if match:
                                cpu_usage = float(match.group(1)) * self.cpu_cores
                                logger.debug(f"CPU使用率: {cpu_usage}% (dumpsys cpuinfo)")
                                return cpu_usage
            except:
                pass

            return None
        except Exception as e:
            logger.error(f"备选CPU获取方法失败: {str(e)}")
            return None

    def get_battery_level(self):
        """获取电池电量百分比 - 增强版本"""
        try:
            output = self.dev.shell("dumpsys battery")
            if not output:
                return None

            # 尝试多种匹配方式
            level_match = re.search(r'level\s*:\s*(\d+)', output)
            if not level_match:
                level_match = re.search(r'current battery level:\s*(\d+)', output)
            if not level_match:
                level_match = re.search(r'Battery level:\s*(\d+)', output)
            if not level_match:
                level_match = re.search(r'charge level:\s*(\d+)', output)
            if not level_match:
                # 尝试匹配百分比数字
                level_match = re.search(r'\b(\d+)%\b', output)

            if level_match:
                battery_level = int(level_match.group(1))
                logger.debug(f"获取电量成功: {battery_level}%")
                return battery_level

            logger.debug(f"未找到电量信息: {output[:200]}")
            return None
        except Exception as e:
            logger.debug(f"获取电量情况失败: {str(e)}")
            return None

    def get_phone_temperature(self):
        """获取手机温度(摄氏度)"""
        try:
            output = self.dev.shell("dumpsys battery")
            if not output:
                return None

            match = re.search(r'temperature\s*:\s*(\d+)', output)
            if match:
                return float(match.group(1)) / 10.0
            return None
        except Exception as e:
            logger.debug(f"获取手机温度情况失败: {str(e)}")
            return None

    def get_fps(self):
        """添加平滑处理的FPS获取逻辑"""
        try:
            raw_fps = self._get_raw_fps()

            # 平滑处理
            if not hasattr(self, '_fps_history'):
                self._fps_history = []

            self._fps_history.append(raw_fps)

            if len(self._fps_history) > 5:
                self._fps_history.pop(0)

            smoothed_fps = sum(self._fps_history) / len(self._fps_history)

            # 确保FPS在合理范围内
            if smoothed_fps < 1:
                return 1.0
            if smoothed_fps > 120:
                return 120.0

            return round(smoothed_fps, 1)
        except Exception as e:
            logger.error(f"平滑处理FPS失败: {str(e)}")
            return self.get_screen_refresh_rate()

    @retry(times=2, delay=1)
    def _get_raw_fps(self):
        """原始FPS获取逻辑 - 增强错误处理"""
        try:
            # 方法1: 使用gfxinfo直方图数据
            try:
                output = self.dev.shell(f"dumpsys gfxinfo {self.package_name}")
                if output:
                    # 解析直方图数据
                    histogram = {}
                    for line in output.splitlines():
                        if "HISTOGRAM:" in line:
                            parts = line.split("HISTOGRAM:")[1].strip().split()
                            for part in parts:
                                if '=' in part:
                                    ms_str, count_str = part.split('=')
                                    try:
                                        ms = int(ms_str.replace('ms', ''))
                                        count = int(count_str)
                                        histogram[ms] = count
                                    except:
                                        continue
                            break

                    # 计算平均帧时间
                    if histogram:
                        total_count = 0
                        total_time_ms = 0

                        for ms, count in histogram.items():
                            total_count += count
                            total_time_ms += ms * count

                        if total_count > 0:
                            avg_frame_time_ms = total_time_ms / total_count
                            fps = 1000 / avg_frame_time_ms
                            logger.debug(f"FPS: {fps} (gfxinfo)")
                            return fps
            except Exception as e:
                logger.debug(f"gfxinfo方法失败: {str(e)}")

            # 方法2: 使用SurfaceFlinger
            try:
                self.dev.shell("dumpsys SurfaceFlinger --latency-clear")
                time.sleep(0.5)  # 增加等待时间
                output = self.dev.shell("dumpsys SurfaceFlinger --latency")

                if output:
                    lines = output.strip().split('\n')
                    if len(lines) >= 10:
                        timestamps = []
                        for line in lines[1:]:
                            if not line.strip():
                                continue
                            parts = line.split()
                            if len(parts) > 0:
                                try:
                                    ts = int(parts[0])
                                    if ts > 0:
                                        timestamps.append(ts)
                                except:
                                    continue

                        if len(timestamps) >= 5:
                            start_time = min(timestamps) / 1e9
                            end_time = max(timestamps) / 1e9
                            duration = end_time - start_time

                            if duration > 0:
                                fps = len(timestamps) / duration
                                logger.debug(f"FPS: {fps} (SurfaceFlinger)")
                                return fps
            except Exception as e:
                logger.debug(f"SurfaceFlinger方法失败: {str(e)}")

            # 方法3: 使用屏幕刷新率作为最终回退
            refresh_rate = self.get_screen_refresh_rate()
            logger.debug(f"使用屏幕刷新率作为FPS: {refresh_rate}")
            return refresh_rate

        except Exception as e:
            logger.error(f"获取原始FPS失败: {str(e)}")
            # 返回屏幕刷新率作为最终回退
            return self.get_screen_refresh_rate()

    def get_screen_refresh_rate(self):
        """获取设备屏幕刷新率"""
        try:
            # 方法1: SurfaceFlinger
            output = self.dev.shell("dumpsys SurfaceFlinger | grep 'Refresh rate'")
            if output:
                match = re.search(r'(\d+\.\d+) fps', output)
                if match:
                    return float(match.group(1))

            # 方法2: Window管理器
            output = self.dev.shell("dumpsys window | grep mRefreshRate")
            if output:
                match = re.search(r'mRefreshRate=(\d+\.\d+)', output)
                if match:
                    return float(match.group(1))

            # 方法3: 显示服务
            output = self.dev.shell("dumpsys display | grep refreshRate")
            if output:
                match = re.search(r'refreshRate\s*=\s*(\d+\.?\d*)', output)
                if match:
                    return float(match.group(1))

            # 默认值
            return 60.0
        except:
            return 60.0

    def start_monitoring(self, interval=3):
        """开始性能监控，包含虚拟内存"""
        self._monitoring = True
        self.performance_data = []
        self._last_sample_time = time.time()
        self.exceeded_thresholds = []
        while self._monitoring:

            logger.info(f"启动性能监控，包名: {self.package_name}, 间隔: {interval}秒")

            # 初始化CPU时间基准
            try:
                # 初始化/proc/stat基准
                sys_stat = self.dev.shell("cat /proc/stat | grep '^cpu '")
                if sys_stat:
                    sys_parts = sys_stat.split()
                    self._last_sys_time = sum(int(sys_parts[i]) for i in range(1, 8))

                # 初始化进程CPU时间基准
                if self.pid:
                    proc_stat = self.dev.shell(f"cat /proc/{self.pid}/stat")
                    if proc_stat:
                        proc_parts = proc_stat.split()
                        self._last_proc_time = sum(int(proc_parts[i]) for i in [13, 14, 15, 16])
            except Exception as e:
                logger.debug(f"初始化CPU基准失败: {str(e)}")

            while self._monitoring:
                timestamp = time.strftime("%Y-%m-%d %H:%M:%S")

                # 在每次循环开始时检查应用状态
                if not self.is_app_running():
                    self._monitoring = False
                    break

                # 收集数据
                memory = self.get_memory_usage(include_virtual=True)
                cpu = self.get_cpu_usage()
                battery = self.get_battery_level()
                temperature = self.get_phone_temperature()
                fps = self.get_fps()

                # 记录调试信息
                logger.debug(
                    f"性能数据: 时间={timestamp}, "
                    f"内存(RSS)={memory['rss'] if memory and 'rss' in memory else 'N/A'}KB, "
                    f"内存(VIRT)={memory['virt'] if memory and 'virt' in memory else 'N/A'}KB, "
                    f"CPU={cpu}%, "
                    f"电量={battery}%, "
                    f"温度={temperature}°C, "
                    f"FPS={fps}"
                )

                # 保存数据
                data = {
                    "timestamp": timestamp,
                    "memory": memory,
                    "cpu": cpu,
                    "battery": battery,
                    "temperature": temperature,
                    "fps": fps
                }
                self.performance_data.append(data)

                time.sleep(interval)

    def stop_monitoring(self):
        """停止性能监控"""
        self._monitoring = False
        return len(self.performance_data) > 0

    def get_exceeded_thresholds(self):
        """获取所有超阈值记录"""
        return self.exceeded_thresholds